import { asyncRoutes, constantRoutes } from '@/router'

/**
 * Use meta.role to determine if the current user has permission
 * @param authority
 * @param route
 */
function hasPermission(authority, route) {
    if (route.meta && route.meta.role)
        return authority >> route.meta.role & 1
    return true
}

/**
 * Filter asynchronous routing tables by recursion
 * @param routes asyncRoutes
 * @param authority
 */
export function filterAsyncRoutes(routes, authority) {
    const res = []

    routes.forEach(route => {
        const tmp = { ...route }
        if (hasPermission(authority, tmp) == true) {
            if (tmp.children)
            {
                tmp.children = filterAsyncRoutes(tmp.children, authority)
                if(tmp.children.length > 0 )
                res.push(tmp)
            }
            else
            res.push(tmp)
        }
    })

    return res
}

const state = {
    routes: [],
    addRoutes: []
}

const mutations = {
    SET_ROUTES: (state, routes) => {
        state.addRoutes = routes
        state.routes = constantRoutes.concat(routes)
    }
}

const actions = {
    generateRoutes({ commit }, authority) {
        return new Promise(resolve => {
            let accessedRoutes = filterAsyncRoutes(asyncRoutes, authority)
            commit('SET_ROUTES', accessedRoutes)
            resolve(accessedRoutes)
        })
    }
}

export default {
    namespaced: true,
    state,
    mutations,
    actions
}